﻿using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using xbd.DataConvertLib;

namespace TaoYL.BoosterStation
{
    public partial class FrmReport : Form
    {
        public FrmReport()
        {
            InitializeComponent();
            this.cmb_ReportType.Items.Add("小时报表");
            this.cmb_ReportType.Items.Add("日报表");
            this.cmb_ReportType.SelectedIndex = 0;

            ///初始化条件
            InitialColumnList();
        }

        #region Field
        private List<string> maxCondition = new List<string>();
        private List<string> minCondition = new List<string>();
        private List<string> avgCondition = new List<string>();
        private HistoryDataService historyDataService = HistoryDataService.Instance;
        #endregion
        private void InitialColumnList()
        {
            List<string> columnList = new List<string>();
            columnList.Add("PressureIn");
            columnList.Add("PressureOut");
            columnList.Add("TempIn1");
            columnList.Add("TempIn2");
            columnList.Add("TempOut");
            columnList.Add("PressureTank1");
            columnList.Add("PressureTank2");
            columnList.Add("LevelTank1");
            columnList.Add("LevelTank2");
            columnList.Add("PressureTankOut");

            foreach (var item in columnList)
            {
                maxCondition.Add($"Max ({item})");
                minCondition.Add($"Min ({item})");
                avgCondition.Add($"Avg ({item})");
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 无边框拖动 

        private Point mPoint;
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }

        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }
        #endregion

        private void cmb_ReportType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.cmb_ReportType.SelectedIndex)
            {
                case 0:
                    this.dtp_ReportTime.CustomFormat = "yyyy-MM-dd HH:00:00";
                    break;
                case 1:
                    this.dtp_ReportTime.CustomFormat = "yyyy-MM-dd 00:00:00";
                    break;
                default:
                    this.dtp_ReportTime.CustomFormat = "yyyy-MM-dd HH:00:00";
                    break;
            }
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            //时间段
            List<string> startTime = new List<string>();
            List<string> endTime = new List<string>();

            DateTime dateTime =Convert.ToDateTime( this.dtp_ReportTime.Text);

            switch (this.cmb_ReportType.SelectedIndex)
            {
                case 0:
                    for (int i = 0; i < 60; i++)
                    {
                        startTime.Add(dateTime.AddMinutes(i).ToString("yyyy-MM-dd HH:00:00"));
                        endTime.Add(dateTime.AddMinutes(i + 1).ToString("yyyy-MM-dd HH:59:59"));
                    }
                    break;
                case 1:
                    for (int i = 0; i < 24; i++)
                    {
                        startTime.Add(dateTime.AddHours(i).ToString("yyyy-MM-dd 00:00:00"));
                        endTime.Add(dateTime.AddHours(i + 1).ToString("yyyy-MM-dd 23:59:59"));
                    }
                    break;
                default:
                    break;
            }



            //条件
            List<string> conditionList = this.rdb_Max.Checked ? maxCondition :
                this.rdb_Min.Checked ? minCondition : avgCondition;

            //查询
            Task.Run(() =>
            {
                Task<OperateResult<DataTable>>[] taskList = new Task<OperateResult<DataTable>>[startTime.Count];

                for (int i = 0; i < taskList.Length; i++)
                {
                    taskList[i] = Task.Factory.StartNew((index) =>
                    {
                        return historyDataService.GetReportDataByCondition(startTime[(int)index], endTime[(int)index], conditionList, index.ToString());
                    }, i);
                }

                Task<OperateResult<DataTable>[]> task = Task.WhenAll(taskList);

                if (task.Result.Length > 0 && task.Result.First().IsSuccess)
                {
                    //希望得到一个DataTable
                    DataTable dataTable = GetAllDataTable(task.Result);

                    //再把dataTable显示到dgv
                    if (dataTable!=null)
                    {
                        UpdateDataTable(dataTable,startTime);
                    }
                    else
                    {
                        this.Invoke(new Action(() =>
                        {
                            //提示没有数据
                            new MsgBoxConfirm("数据查询", "查询数据表为空!").ShowDialog();
                        }));
                    }

                }
                else
                {
                    this.Invoke(new Action(() =>
                    {
                        //提示没有数据
                        new MsgBoxConfirm("数据查询", "此时间段内未查询到数据").ShowDialog();
                    }));
                }
            });

        }

        private void UpdateDataTable(DataTable dataTable, List<string> startTime)
        {
            //操作dgv
            if (dataGridView_history.InvokeRequired)
            {
                dataGridView_history.Invoke(new Action<DataTable, List<string>>(UpdateDataTable), dataTable, startTime);
            }
            else
            {
                this.dataGridView_history.Rows.Clear();

                //dataGridView_history第一列新增插入时间
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    int rowIndex = dataGridView_history.Rows.Add();
                    dataGridView_history.Rows[rowIndex].Cells[0].Value = startTime[i];
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        if (dataTable.Rows[rowIndex][j] is DBNull)
                        {
                            dataGridView_history.Rows[rowIndex].Cells[j + 1].Value = "---";
                        }
                        else
                        {
                            dataGridView_history.Rows[rowIndex].Cells[j + 1].Value = dataTable.Rows[rowIndex][j];
                        }
                        
                    }
                }
            }
        }

        private DataTable GetAllDataTable(OperateResult<DataTable>[] dataResult)
        {
            //获取所有成功的DataTable的集合
            List<DataTable> dataTables = new List<DataTable>();

            foreach (var item in dataResult)
            {
                if (item.IsSuccess)
                {
                    dataTables.Add(item.Content);
                }
            }

            if (dataTables.Count>0)
            {
                //排序
                dataTables=dataTables.OrderBy(c=>Convert.ToInt32(c.TableName)).ToList();

                //再把DataTable合并
                //赋值已有表结构
                DataTable resultTable = dataTables[0].Clone();

                object[] rowData = new object[resultTable.Columns.Count];

                //foreach (var item in dataTables)
                //{
                //    for (int i = 0; i < item.Rows.Count; i++)
                //    {
                //        for (int j = 0; j < resultTable.Columns.Count; j++)
                //        {
                //            rowData[j] = item.Rows[i][j];
                //        }
                //        resultTable.Rows.Add(rowData);
                //    }
                //}

                for (int i = 0; i < dataTables.Count; i++)
                {
                    for (int j = 0; j < dataTables[i].Rows.Count; j++)
                    {
                        dataTables[i].Rows[j].ItemArray.CopyTo(rowData, 0);
                        resultTable.Rows.Add(rowData);
                    }
                }
                return resultTable;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// dgv行序号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_history_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint(this.dataGridView_history,e);
        }

        private void btn_Export_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //标题
            saveFileDialog.Title = "请选择文件";
            saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|CSV文件(*.csv)|*.csv";
            saveFileDialog.FilterIndex = 1;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName = "数据报表_" +this.cmb_ReportType.Text+"_"+ Convert.ToDateTime(this.dtp_ReportTime.Text).ToString("yyyyMMddHHmmss");

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    MiniExcel.SaveAsAsync(saveFileDialog.FileName, GetHistoryDataFrmDgv());
                }
                catch (Exception ex)
                {
                    new MsgBoxConfirm("数据导出", "导出失败:" + ex.Message).ShowDialog();
                }
            }
        }

        private List<HistoryData> GetHistoryDataFrmDgv()
        {
            if (dataGridView_history.Rows.Count>0)
            {
                List<HistoryData> historyDatas = new List<HistoryData>();
                foreach (DataGridViewRow item in dataGridView_history.Rows)
                {
                    historyDatas.Add(new HistoryData()
                    {
                        InsertTime = Convert.ToDateTime(item.Cells[0].Value),
                        PressureIn = Convert.ToSingle(item.Cells[1].Value),
                        PressureOut = Convert.ToSingle(item.Cells[2].Value),
                        TempIn1 = Convert.ToSingle(item.Cells[3].Value),
                        TempIn2 = Convert.ToSingle(item.Cells[4].Value),
                        TempOut = Convert.ToSingle(item.Cells[5].Value),
                        PressureTank1 = Convert.ToSingle(item.Cells[6].Value),
                        PressureTank2 = Convert.ToSingle(item.Cells[7].Value),
                        LevelTank1 = Convert.ToSingle(item.Cells[8].Value),
                        LevelTank2 = Convert.ToSingle(item.Cells[9].Value),
                        PressureTankOut = Convert.ToSingle(item.Cells[10].Value)
                    });
                }
                return historyDatas;
            }
            else
            {
                return new List<HistoryData>();
            }
        }
    }
}
